//#region dom元素
const tbody = document.querySelector('tbody')
const updateForm = document.querySelector('.update-form')
const addForm = document.querySelector('.add-form')
const addBtn = document.querySelector('.add-btn')

const provinceUpdate = updateForm.querySelector('select[name="province"]')
const cityUpdate = updateForm.querySelector('select[name="city"]')
const countyUpdate = updateForm.querySelector('select[name="county"]')

const provinceAdd = addForm.querySelector('select[name="province"]')
const cityAdd = addForm.querySelector('select[name="city"]')
const countyAdd = addForm.querySelector('select[name="county"]')
//#endregion

getStudents()

//#region 渲染表格函数***************************************************
function getStudents() {
  axios.get('/student/list').then(result => {
    let html = ``
    let arr = result.data.data
    html = arr
      .map(
        item => `<tr>
    <th scope="row">${item.id}</th>
    <td>${item.name}</td>
    <td>${item.age}</td>
    <td>${item.sex}</td>
    <td>${item.group}</td>
    <td>${item.phone}</td>
    <td>${item.salary}</td>
    <td>${item.truesalary}</td>
    <td>${item.province}${item.city}${item.county}</td>
    <td>
      <button type="button" data-id=${item.id} class="btn btn-primary btn-sm update-btn" data-bs-toggle="modal" data-bs-target="#updateModal">修改</button>
      <button type="button" data-id=${item.id} class="btn btn-danger btn-sm del-btn">删除</button>
    </td>
  </tr>`
      )
      .join('')
    tbody.innerHTML = html
  })
}
//#endregion********************************************************

//#region 提交添加表单*************************************************
//点击添加按钮，就要渲染省份列表
addBtn.addEventListener('click', function () {
  renderProvince(provinceAdd)
})
addForm.addEventListener('submit', function (e) {
  e.preventDefault()
  const data = $(addForm).serialize()
  console.log(data)
  axios.post('/student/add', data).then(result => {
    if (result.data.code === 0) {
      $('#addModal').modal('hide')
      getStudents()
      toastr.success(result.data.message)
      addForm.reset() //重置表单
    } else {
      toastr.error(result.data.message)
    }
  })
})
addForm.addEventListener('reset', function () {
  renderOption([], cityAdd)
  renderOption([], countyAdd)
})
//#endregion*******************************************

//#region 提交修改表单**************************************
updateForm.addEventListener('submit', function (e) {
  e.preventDefault()
  const fd = new FormData(this)
  const data = $(updateForm).serialize()
  axios.put('/student/update', data).then(result => {
    if (result.data.code === 0) {
      toastr.success(result.data.message)
      $('#updateModal').modal('show')
      getStudents()
    } else {
      toastr.error(result.data.message)
    }
  })
})
//#endregion***************************************

//#region 委托给tbody  点击按钮删除数据 修改数据***************************************
tbody.addEventListener('click', function (e) {
  if (e.target.classList.contains('update-btn')) {
    //修改学生信息开始
    //根据id发请求获取该项数据
    const id = e.target.dataset.id
    const query = '?id=' + id
    axios.get('/student/one' + query).then(result => {
      const obj = result.data.data
      const {
        province,
        city,
        county
      } = obj
      //填input输入框的初始值
      for (const key in obj) {
        //满足条件设置，不满足就跳过
        const dom = updateForm.querySelector(`[name="${key}"]`)
        if (key === 'sex' || !dom) { //性别 或找不到dom元素就跳过
          continue
        }
        dom.value = obj[key]
      }

      updateForm.querySelector(`[name=sex][value="${obj.sex}"]`).checked = true
      //填省份初始值  同时应该渲染好市的下拉选项
      renderProvince(provinceUpdate, province) //点击修改按钮，就渲染修改表单里的省份列表
      renderCity(province, cityUpdate, city)
      renderCounty(province, city, countyUpdate, county)
    })
    //修改学生信息结束
  } else if (e.target.classList.contains('del-btn')) {
    //删除开始****************************************************************
    const query = `?id=${e.target.dataset.id}`
    axios.delete('/student/delete' + query).then(result => {
      if (result.data.code === 0) {
        toastr.success(result.data.message)
      } else {
        toastr.error(result.data.message)
      }
      getStudents()
    })
  }
})
//#endregion*********************************************

//#region 地方下拉框改变触发事件，渲染下级数据***************************************
//省改变，渲染市列表，清空县列表
provinceUpdate.addEventListener('change', function () {
  renderCity(provinceUpdate.value, cityUpdate)
  renderOption([], countyUpdate) //改变了省份，还没有选择市选项，无法渲染县列表，清空下拉选项



})
provinceAdd.addEventListener('change', function () {
  renderCity(provinceAdd.value, cityAdd)
  renderOption([], countyAdd) //改变了省份，还没有选择市选项，无法渲染县列表，清空下拉选项
})
// 市改变，渲染县列表
cityUpdate.addEventListener('change', function () {
  renderCounty(provinceUpdate.value, cityUpdate.value, countyUpdate)
})
cityAdd.addEventListener('change', function () {
  renderCounty(provinceAdd.value, cityAdd.value, countyAdd)
})

//#endregion*****************************************************

//#region renderProvince函数：可以渲染两个模态框的省份列表
function renderProvince(dom, province) {
  axios.get('/geo/province').then(result => {
    let arr = result.data
    renderOption(arr, dom)
    //修改表单里，取得了省份值，渲染列表的同时选中该项省份
    province && (dom.value = province)
  })
}
//#endregion

//#region  renderCity(province, dom, city)接受省份和一个省份的select元素，根据省份渲染市选项**********************
function renderCity(province, dom, city) {
  const jquery = '?pname=' + province
  axios.get('/geo/city' + jquery).then(result => {
    let arr = result.data
    renderOption(arr, dom)
    city && (dom.value = city) //接受第三个参数 可选，有择选中参数指定项

    //如果市只有一个项（直辖市），选中该项，直接可以渲染县
    if (arr.length === 1) {
      city = dom.value = dom.querySelectorAll(`option`)[1].value //给city赋值
      const form = $(dom).parents('form')[0]
      const countyDom = form.querySelector('select[name="county"]')
      renderCounty(province, city, countyDom)
    }
  })
}
//#endregion**************************************************

//#region renderCounty(province, city, dom, county)************************************
function renderCounty(province, city, dom, county) {
  const jquery = `?pname=${province}&cname=${city}`
  return axios.get('/geo/county' + jquery).then(result => {
    let arr = result.data
    renderOption(arr, dom)
    county && (dom.value = county) //接受第三个参数 可选，有择选中参数指定项
  })
}
//#endregion*********************************************************

//#region  renderOption(arr, dom)渲染数组进option列表里************************************
function renderOption(arr, dom) {
  if (dom.name === 'city') {
    dom.innerHTML = `<option selected value="">--市--</option>`
  } else if (dom.name === 'county') {
    dom.innerHTML = `<option selected value="">--县--</option>`
  } else if (dom.name === 'province') {
    dom.innerHTML = `<option selected value="">--省--</option>`
  }
  let array = arr || [] //出现arr为空的情况
  let html = array
    .map(item => `<option value="${item}">${item}</option>`)
    .join('')
  dom.innerHTML += html
}
//#endregion**********************************************************